<template>
  <!-- 手动新增欠料单 -->
  <div>
    <FormPanel ref="form" :labelWidth="100" :isSubmitBtn="false" :list="formList"></FormPanel>
    <div class="btnWrap">
      <el-button @click="handleClose">取消</el-button>
      <AjaxButton type="primary" :click="handleConfirm">保存</AjaxButton>
    </div>

    <!-- 配件选择弹窗 -->
    <BaseDialog :visible.sync="partSelectVisible" title="选择配件" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <partSelect mode="single" :fetchapi="partSelectFetchApi" @close="partSelectVisible = false" @onConfirm="handleDetailSelectConfirm" />
    </BaseDialog>

    <!-- 库位选择弹窗 -->
    <BaseDialog width="30%" :visible.sync="positionSelectVisible" title="选择库位" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <position :params="positionFetchParam" @close="positionSelectVisible = false" @onConfirm="handlePositionConfirm" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { notifyAction, confirmAction } from '@/utils';

import { addNewIndebtPartDetail, queryEditDataBySortId, getUserListSelect } from '@/api/part/partOther/lackDetail';
import { queryPartListByOrderType } from '@/api/part/partPurchase/purchaseOrder';
import { getStroageList } from '@/api/part/partOutbound/partBreak';
import { queryUsableLocations } from '@/api/part/inventoryManager/inventoryManager/index';
import { getLingLiaoRenSelect } from '@/api/part/partOutbound/repairMaterials/dict';
import { queryParyHasStorageById } from '@/api/part/common';
import { exportExcelFile, arrayObjDeWeight } from '@/utils/index';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import { getAllUser } from '@/api/customerRepair/usedCarVisit/resultEntry';
import dictCode from '@/utils/dictCode';

import partSelect from '@/pages/part/partPurchase/purchaseOrder/partSelect';
import position from '@/pages/part/common/position';

export default {
  components: {
    partSelect,
    position
  },
  mixins: [dictionary],
  props: ['type', 'shortId'],
  data() {
    return {
      formList: this.createFormList(),
      partSelectFetchApi: queryPartListByOrderType,
      partSelectVisible: false, // 是否显示配件选择弹窗,
      formData: {},
      positionSelectVisible: false, // 是否显示库位选择弹窗
      positionFetchParam: {} // 库位选择查询参数
    };
  },
  computed: {
    storageAndPart() {
      return {
        storageCode: this.formList.find(item => item.fieldName == 'storageCode').initialValue,
        partNo: this.formList.find(item => item.fieldName == 'partNo').initialValue
      };
    }
  },
  watch: {
    storageAndPart: {
      handler(newVal, oldVal) {
        this.formList.find(item => item.fieldName == 'storagePositionCode').disabled = !!!(newVal.partNo && newVal.storageCode && this.type != 'edit');
        if (newVal.partNo && newVal.storageCode) {
          // this.quertSrotagePositionByStorage();
        }
      },
      deep: true
    }
  },
  created() {
    this.queryAllStorage();
    this.getLingLiaoRenSelect();
    this.queryServeseList();
    if (this.type == 'edit') {
      this.initEditData();
    }
  },
  methods: {
    // 获取表单数据
    getFormData(val) {
      console.log(val);
      this.formData = val;
    },
    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '仓库代码',
          fieldName: 'storageCode',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '库位代码',
          fieldName: 'storagePositionCode',
          disabled: true,
          itemList: [],
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.handlePositionSelect}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName',
          placeholder: '请选择',
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.handlePartSelecterClick}></el-button>;
          },
          readonly: true
          // rules: [{ required: true, message: '请选择配件', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo',
          disabled: true
          // rules: [{ required: true, message: '配件代码不能为空', trigger: 'blur' }]
        },
        {
          type: 'SELECT',
          label: '出库类型',
          fieldName: 'inOutType',
          itemList: this.createDictList(8249)
        },
        {
          type: 'SELECT',
          label: '缺料类型',
          fieldName: 'shortType',
          itemList: this.createDictList(8134)
        },
        {
          type: 'INPUT',
          label: '单据号码',
          fieldName: 'sheetNo'
        },
        {
          type: 'SELECT',
          label: '是否已结案',
          fieldName: 'closeStatus',
          itemList: this.createDictList('1004')
        },
        // {
        //   type: 'SELECT',
        //   label: '是否急件',
        //   fieldName: 'isUrgent',
        //   itemList: this.createDictList('1004')
        // },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license'
        },
        {
          type: 'INPUT_NUMBER',
          label: '缺料数量',
          fieldName: 'shortQuantity',
          min: 0.01,
          precision: 2,
          initialValue: 1
          // rules: [{ required: true, message: '请输入需求数量', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName'
        },
        // {
        //   type: 'INPUT',
        //   label: '电话',
        //   fieldName: 'phone'
        // },
        // {
        //   type: 'SELECT',
        //   label: '主修人', // 领料人
        //   fieldName: 'majorPerson',
        //   itemList: [],
        //   rules: [{ required: true, message: '请输入欠料明细描述', trigger: 'blur' }]
        // },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'servicePerson',
          itemList: []
        },
        {
          type: 'DATE',
          label: '到货日期',
          fieldName: 'inDate'
        },
        {
          type: 'DATE',
          label: '维修日期',
          fieldName: 'roDate'
        }
        // {
        //   type: 'INPUT',
        //   label: '欠料明细描述',
        //   fieldName: 'remarks',
        //   selfCols: 2,
        //   rules: [{ required: true, message: '请输入欠料明细描述', trigger: 'blur' }]
        // }
      ];
    },
    // 查询所有仓库
    async queryAllStorage() {
      let res = await getStroageList();
      this.formList.find(item => item.fieldName == 'storageCode').itemList = res.data.map(item => ({ text: item.STORAGE_NAME, value: item.STORAGE_CODE }));
    },
    // 根据仓库查询库位
    async quertSrotagePositionByStorage() {
      let partNo = this.formList.find(item => item.fieldName == 'partNo').initialValue;
      let storageCode = this.formList.find(item => item.fieldName == 'storageCode').initialValue;

      let res = await queryUsableLocations({
        storageCode,
        partNo
      });
      if (res.resultCode == 200) {
        if (res.data[0].error) {
          notifyAction(res.data[0].error, 'warning');
        } else {
          this.formList.find(item => item.fieldName == 'storagePositionCode').itemList = res.data.map(item => ({ text: item.storagePositionCode, value: item.storagePositionCode }));
        }
      }
    },
    // 点击查询库位
    async handlePositionSelect() {
      let partNo = this.formList.find(item => item.fieldName == 'partNo').initialValue;
      let storageCode = this.formList.find(item => item.fieldName == 'storageCode').initialValue;
      let res = await queryParyHasStorageById({ storageCode, partNo });
      console.log(res);
      if (res.resultCode == 200) {
        if (res.data.length) {
          this.formList.find(item => item.fieldName == 'storagePositionCode').initialValue = res.data[0].storagePositionCode;
          notifyAction('此配件在此仓库存在库位，已自动赋值', 'success');
        } else {
          this.positionFetchParam = {
            storageCode,
            partNo
          };
          this.positionSelectVisible = true;
        }
      }
    },
    // 库位选择点击确定
    handlePositionConfirm(e) {
      console.log(e);
      this.formList.find(item => item.fieldName == 'storagePositionCode').initialValue = e[0].storagePositionCode;
    },
    // 查询领料人
    async getLingLiaoRenSelect() {
      let res = await getAllUser();
      if (res.resultCode == 200) {
        let data = arrayObjDeWeight(res.data, 'userId');
        this.formList.find(item => item.fieldName == 'majorPerson').itemList = data.map(item => ({ text: item.employeeName, value: item.userId + '' }));
      }
    },
    // 获取服务顾问列表
    async queryServeseList() {
      let role = { role: dictCode.SERVICE_CONSULTANT };
      let res = await searchRoleByCode(role);
      if (res.resultCode == 200) {
        this.formList.find(item => item.fieldName == 'servicePerson').itemList = res.data.map(item => ({ text: item.employeeName, value: item.userId + '' }));
      }
    },
    // 点击配件搜索按钮
    handlePartSelecterClick() {
      this.partSelectVisible = true;
    },
    // 配件选择点击确定
    handleDetailSelectConfirm(e) {
      this.partSelectVisible = false;
      this.formList.find(item => item.fieldName == 'partName').initialValue = e[0].partName;
      this.formList.find(item => item.fieldName == 'partNo').initialValue = e[0].partNo;
    },
    // 点击取消
    handleClose() {
      this.$emit('close');
    },
    // 初始化编辑数据
    async initEditData() {
      let res = await queryEditDataBySortId(this.shortId);
      if (res.resultCode == 200) {
        this.formList.map(item => {
          item.initialValue = res.data[item.fieldName];
        });
      }
      this.formList.find(x => {
        if (x.fieldName != 'closeStatus') {
          x.disabled = true;
        }
      });
    },
    // 点击确定
    async handleConfirm() {
      let formData = this.$refs.form.SUBMIT_FORM();
      console.log(123, formData);
      if (formData == null) {
        return;
      }
      formData.inDate = formData.inDate ? formData.inDate.split(' ')[0] : '';
      formData.roDate = formData.roDate ? formData.roDate.split(' ')[0] : '';
      if (this.type == 'edit') {
        formData.shortId = this.shortId;
      }
      let res = await addNewIndebtPartDetail(formData);
      if (res.resultCode == 200) {
        this.$emit('researchTableData');
      }
    }
  }
};
</script>

<style scoped>
.btnWrap {
  position: absolute;
  left: 0px;
  bottom: 0px;
  right: 0px;
  z-index: 9;
  border-top: 1px solid rgb(233, 233, 233);
  padding: 10px 20px;
  background: rgb(255, 255, 255);
  text-align: right;
}
</style>
